/**
 * Created by TRwin7SP1 on 2016/8/15.
 */
angular.module('inspinia')
  .controller('EBPController', function ($scope, $timeout, $log, values, throttleFn, $interval, $element, $http) {

   
    // var stuffServeIPHome = "http://192.168.0.102";
    var stuffServeIPHome = "http://192.168.100.111";
    // var stuffServeIPWork = "http://192.168.100.113";
    var structuresList = null;
    $('body').addClass('mini-navbar');

    init();

    function init() {
      /*
       jsTree初始化
       */
      $http.get(lm.environment("RTlocalserver").hostUrl+"/api/structure/DVH", {
        headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
      }).success(function (data) {
        structuresList = data;
        // $log.debug(structuresList);
        var nodeNum = 7;//image struct节点的个数
        var clientHeight = document.documentElement.clientHeight;

        $scope.treeConfig5 = {
          'plugins': ['types', 'dnd', "checkbox"],
          'types': {
            'default': {
              'icon': 'fa fa-folder'
            },
            'html': {
              'icon': 'fa fa-file-code-o'
            },
            'svg': {
              'icon': 'fa fa-file-picture-o'
            },
            'css': {
              'icon': 'fa fa-file-code-o'
            },
            'img': {
              'icon': 'fa fa-file-image-o'
            },
            'js': {
              'icon': 'fa fa-file-text-o'
            }

          }
        };
        $scope.treeData5 = [
          {
            "id": "ajson1",
            "parent": "#",
            "text": "image：TRstruct",
            "state": {
              "opened": true
            },
            "__uiNodeId": 1
          }, {
            "id": "ajson2",
            "parent": "ajson1",
            "text": "Registered Images",
            "state": {
              "opened": true
            },
            "__uiNodeId": 2
          }, {
            "id": "ajson3",
            "parent": "ajson2",
            "text": "Structure Set:CT_1",
            "state": {
              "opened": true
            },
            "type": "css",
            "__uiNodeId": 3
          },
          {
            "id": "RTstruct",
            "parent": "ajson1",
            "text": "Structure Set:RTstruct",
            "state": {
              "opened": true
            },
            "__uiNodeId": 6
          },

        ];

        /*
         js颜色选择
         */
        angular.forEach(structuresList, function (data, index, array) {
          var _obj = {
            "id": data.dvhName,
            "parent": "RTstruct",
            "text": data.name,
            "state": {
              "opened": true
            },
            "type": "img",
            "__uiNodeId": nodeNum + index
          }
          $scope.treeData5.push(_obj);
          // $scope.$apply();
          // console.log($scope.treeData5);
        });

        var lisnerHeight = $interval(function () {
          if ($('#TRviewerHeader').height() != null && $('#title').height() != null) {
            $interval.cancel(lisnerHeight);
            $('#imageDiv').css('height', (clientHeight - $('div#TRviewerHeader').height() - $('#title').height() - 5).toString() + 'px');
            // $('#jstree_TRstruct').css('height',(clientHeight-$('div#TRviewerHeader').height()-$('#treeUp').height()-5).toString()+'px');
            $('#Scrollbar_TRstruct').css('height', (clientHeight - $('div#TRviewerHeader').height() - $('#treeUp').height() - 5).toString() + 'px');
            $('img').parent('.mBox-content').css('height', ((clientHeight - $('div#TRviewerHeader').height() - 3 * $('#title').height() - 13 ) / 3).toString() + 'px');
          }

        }, 50);

        $scope.detailTree = {
          "height": values.screen.Height - 217 - 157,
          "background-color": "#404040",
        };

      })


      $scope.befull = false;//默认不显示全屏
      /*
       滑块配置项
       */
      $scope.verticalSlider2 = {
        minValue: 0,
        maxValue: 8436,
        options: {
          floor: 0,
          ceil: 8436,
          vertical: true,
          // minLimit: 100,
          // maxLimit:5555
          // showTicks: 1000,
          // showTicksValues: true,
        }

      };
      /*
       Echarts配置项
       */
      $("#echartsLine").width = $("#echartsContainer").width();

      $scope.myChart = echarts.init(document.getElementById('echartsLine'));
      $scope.xdata = [];
      $scope._echartWidth='76%'
      $scope.option = {
        backgroundColor: 'black',
        title: {
          x: 'center',
          text: 'DVH',
          textStyle: {
            color: '#fff'
          }
        },

        dataZoom: [
          {
            type: 'inside',
            xAxisIndex: [0],
            start: 0,
            end: 100
          },
          {
            id: 'dataZoomX',
            type: 'slider',
            xAxisIndex: [0],
            filterMode: 'filter',
            textStyle: {
              color: "#28c6de"
            }
          },
          // {
          //   id: 'dataZoomY',
          //   type: 'slider',
          //   yAxisIndex: [0],
          //   filterMode: 'filter',
          //   textStyle: {
          //     color: "#28c6de"
          //   }
          // }
        ],
        tooltip: {
          trigger: 'axis'
        },


        legend: {
          data: [],
          orient: 'vertical',
          left: 'right',
          borderColor: 'gray',       // 图例边框颜色
          borderWidth: 1, // 图例边框线宽，单位px，默认为0（无边框）

          backgroundColor:'#eeeeee',
          textStyle: {
            color: "black"
          }
        },

        // toolbox: {
        //   feature: {
        //     saveAsImage: {}
        //   }
        // },
        yAxis: {
          type: 'value',
          textStyle: {
            color: '#fff'
          },
          name:'Volume(%)',
          nameLocation:'middle',
          nameTextStyle:{
            color:'white'
          },
          nameGap:'25',
          splitLine: {
            show: true,
            lineStyle: {
              type: 'dashed'
            }
          },
          axisLine: {
            show: true,
            lineStyle:{
              color:'white'
            }
          },
          axisTick:{
            inside:true
          },
        },
        xAxis: [
          {
            type: 'category',

            name:'Dose(cGy)',
            nameLocation:'middle',
            nameTextStyle:{
              color:'white'
            },
            nameGap:'25',
            boundaryGap: false,
            data: $scope.xdata,
            axisLabel: {
              //X轴刻度配置
              interval: 999 //0：表示全部显示不间隔；auto:表示自动根据刻度个数和宽度自动设置间隔个数
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle:{
                color:'white'
              }
            },
            axisTick:{
              inside:true
            },
          },

        ],

        axisLabel: {
          show: true,
          textStyle: {
            color: '#28c6de',
            align: 'left'
          }
        },
        grid:
          {
            show: true,
            borderWidth:'1',
            borderColor:'white',
            x: '6%',
            y: '7%',
            width: $scope._echartWidth,
            height: '75%',
          },
        series: []
      };
      $scope.countEchart = [];

      // 指定图表的配置项和数据


    }

    /*
     echarts响应改变大小
     */
    window.onresize = throttleFn(function () {
      $("#echartsLine").width = $("#echartsContainer").width();
      $scope.myChart = echarts.init(document.getElementById('echartsLine'));
      // $log.debug($scope._echartWidth)

      $scope.myChart.setOption($scope.option);
      // $("#imageContainer").height=$(window).height() - $("#toolbar").height() - $(".ibox-title").height();
      //
      // lmViewer.ui.resizeCanvas();

    }, 100);


    $scope.compareRange = function (min, max) {
      $timeout.cancel($scope.inputTime)
      $scope.inputTime = $timeout(function () {
        if (min > max) {
          $scope.verticalSlider2.minValue = $scope.verticalSlider2.maxValue;
        }
        if (max > $scope.verticalSlider2.options.ceil) {
          $scope.verticalSlider2.maxValue = $scope.verticalSlider2.options.ceil;
        }
      }, 700)
    }


    /*
     展示dvh曲线
     */

    $scope.showLine = function () {
      //显示曲线
      function showLine() {
        $scope.myChart = echarts.init(document.getElementById('echartsLine'));
        $scope.myChart.setOption($scope.option);
      }

      $scope.ydata = [];
      $scope.selectA = event.target.tagName == 'A' ? true : false;
      // $log.debug($scope.selectA);
      $scope._echart = {
        color: $scope.selectA ? event.target.children[0].style.color : event.target.style.color,
        id: $scope.selectA ? event.target.id.split("_")[0] : event.target.parentNode.id.split("_")[0],
        name: $scope.selectA ? event.target.text : event.target.parentNode.text
      }
      if ($(event.target).hasClass('jstree-clicked')||$(event.target).parent().hasClass('jstree-clicked')) {
        $scope._echartFlag = false;
        angular.forEach($scope.countEchart, function (data, index) {
          if ($scope._echart.id == data.id) {
            $scope._echartFlag = true;
            $scope.option.series.push(data);
            showLine();
          }
        })
        if ($scope._echartFlag == false) {

          $http.get(lm.environment("RTlocalserver").hostUrl+"/api/structure/DVH/" + $scope._echart.id, {
            headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'},
          }).success(function (data) {
            // $log.debug(data.rawDvhData);
            $scope.divData = data.rawDvhData;
            angular.forEach($scope.divData, function (data, index, array) {
              if (index % 2 != 0) {
                $scope.ydata.push((data / $scope.divData[1] * 100).toFixed(2));
                $scope.xdata.push((index + 1) / 2 - 1);
              }
            })

            if ($scope.option.xAxis[0].data.length == 0) {
              $scope.option.xAxis[0].data = $scope.xdata;
            }
            $scope.currentEchart = {
              id: $scope._echart.id,
              name: $scope._echart.name,
              type: 'line',
              data: $scope.ydata,
              itemStyle: {
                normal: {
                  color: $scope._echart.color
                }
              }
            }
            $scope.countEchart.push($scope.currentEchart);
            $scope.option.series.push($scope.currentEchart);
            $scope.option.legend.data.push($scope._echart.name);
            showLine();
// $log.debug(data);
          })
        }
      } else {
        angular.forEach($scope.option.series, function (data, index, array) {
          if ($scope._echart.id == data.id) {
            $scope.s_index = index;
            $scope.option.series.splice($scope.s_index, 1);
            showLine();
          }
        })

      }


    }


    $scope.readyCB = function () {


      $timeout(function () {

        //设置颜色
        angular.forEach(structuresList, function (data, index, array) {

          $('#' + data.dvhName + ">a>i").css('color', 'rgb(' + data.color + ')');
          // $log.debug($('#'+data.dvhName+'>a>i'));
        });
      }, 100);

    }


    /**
     *
     */


    $scope.load_allCB = function () {
      $log.info(" JStree load_allCB is running...");

    }


    var lisnerID = $interval(function () {
      //todo tangzhengxiong 2016/9/22   显示默认序列
      if (lmViewer.data.flag == true) {
      $interval.cancel(lisnerID);
      $scope.treeConfig3 = {
        'plugins': ['types', 'dnd'],
        'types': {
          'default': {
            'icon': 'fa fa-folder'
          },
          'user': {
            'icon': 'fa fa-user'
          },
          'book': {
            'icon': 'fa fa-book'
          },
          'css': {
            'icon': 'fa fa-file-code-o'
          },
          'img': {
            'icon': 'fa fa-file-image-o'
          },
          'js': {
            'icon': 'fa fa-file-text-o'
          }

        }
      };
      $scope.treeData3 = [
        {
          "id": "paitient",
          "parent": "#",
          "text": "Patient:" + lmViewer.data.queryParams.patId,
          "state": {
            "opened": true
          },
          "type": "user",
          "__uiNodeId": 1
        }, {
          "id": "study",
          "parent": "paitient",
          "text": "Study:" + lmViewer.data.queryParams.studyUID,
          "state": {
            "opened": true
          },
          "__uiNodeId": 2
        },

      ];
      angular.forEach(lmViewer.data.series, function (data, index, array) {
        $scope.series = {
          "id": index,
          "clickIndex": index,
          "parent": "study",
          "text": "Series:" + data.seriesDescription + '' + data.numberOfInstances,
          "state": {
            "opened": true
          },
          "type": "book",
          "__uiNodeId": 3 + index
        }
        $scope.treeData3.push($scope.series);
      });
      //序列绑定点击事件
      $('#jstree_demo_div').bind('click.jstree', function (e) {
        var _index = event.target.id.substr(0, 1);
        lmViewer.ctrl.showSeriesByIndex(_index);
      })
      }
    }, 100);

    //工兰按钮信息
    $scope.btns = lmViewer.ui.config.buttons;
    //全屏显示
    $scope.lm_fullscreen = function (index) {
      $scope.befull = !$scope.befull;
      if ($scope.befull == true) {
        var height = $(window).height() - $("#toolbar").height() - $(".ibox-title").height();
        document.getElementsByTagName('body')[0].style.overflow = 'hidden';
        $scope.ibox = {
          'width': $("#totalContainer").width(),
          'height': height,
          'position': 'absolute',
          'float': 'left',
          'z-index': 9999,
        }
        // $log.debug($scope.ibox);
        switch (index) {
          case 1:
            $scope.ibox_2 = {
              'display': 'none'
            }

            $scope.ibox1 = $scope.ibox;

            $("#imageContainer").parent().height = height;
            $("#imageContainer").height = height;
            $(window).trigger('resize');
            $timeout(function () {
              lmViewer.ui.resizeCanvas();
            })

            break;
          case 2:
            $scope.ibox2 = $scope.ibox;
            break;
          case 3:
            $scope.ibox3 = $scope.ibox;
            $scope.ibox_1 = {
              'display': 'none'
            }
            break;
          case 4:

            $scope.ibox_1 = {
              'display': 'none'
            }
            $scope.ibox4 = $scope.ibox;

            $timeout(function () {
              $scope._echartWidth='85%';
              $(window).trigger('resize');
            })
            break;
        }
      } else {
        $scope.ibox_1 = {
          'display': 'block'
        }
        $scope.ibox_2 = {
          'display': 'block'
        }
        $scope.ibox1 = {};
        $scope.ibox2 = {};
        $scope.ibox3 = {};
        $scope.ibox4 = {};
        $(window).trigger('resize');
        $timeout(function () {
          lmViewer.ui.resizeCanvas();
        })
      }
    }


  });
